//
// Created by 86176 on 2021/11/3.
//

#ifndef CHENYUENEW_SESSION_H
#define CHENYUENEW_SESSION_H

#include "IoBuffer.h"
#include "IdleStatus.h"
//#include "IoAcceptor.h"
//#include "DefaultFilterChain.h"
#include <map>
#include <string>
#include <WinSock2.h>
//pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

#define BUFFER_SIZE 1024*4 //缓冲区大小

//每一个投递单元，包含了在套节字上处理I/O操作必要信息
struct CIOCPBuffer
{
    WSAOVERLAPPED ol;

    //SOCKET sClient;			// AcceptEx接收的客户方套节字
    //Session* session;           // AcceptEx接收的客户方套节字
    void* session;

    char *buff;				// I/O操作使用的缓冲区
    int nLen;				// buff缓冲区（使用的）大小

    ULONG nSequenceNumber;	// 此I/O的序列号

    int nOperation;			// 操作类型
#define OP_ACCEPT	1
#define OP_WRITE	2
#define OP_READ		3

    CIOCPBuffer *pNext;
};


class Session {
protected:
    std::map<std::string,std::string> sessionConfigs;

public:
    SOCKADDR_IN addrLocal;			// 连接的本地地址
    SOCKADDR_IN addrRemote;			// 连接的远程地址

    BOOL bClosing;					// 套节字是否关闭

    int nOutstandingRecv;			// 此套节字上抛出的重叠操作的数量
    int nOutstandingSend;


    ULONG nReadSequence;			// 安排给接收的下一个序列号
    ULONG nCurrentReadSequence;		// 当前要读的序列号
    CIOCPBuffer *pOutOfOrderReads;	// 记录没有按顺序完成的读I/O

    CRITICAL_SECTION Lock;			// 保护这个结构

    unsigned short packetLen;
    IoBuffer *ioBuffer;
    IdleStatus *idleStatus;
    WSABUF wsabuf;
    DWORD ioRecv;
    DWORD lpFlags;
    SOCKET socket;
    int type;
    struct sockaddr_in si;
    OVERLAPPED Olp;
    DWORD firstRec;


public:

    Session();
    ~Session();
    explicit Session(int sessionId);
    IoBuffer *getIoBuffer() const;

//    DefaultFilterChain defaultFilterChain;
    int key = 2;
protected:
    void buildFilterChain();

};


#endif //CHENYUENEW_SESSION_H
